//
//  AppDelegate.m
//  SpeedLife
//
//  Created by 喻飞 on 15/12/22.
//  Copyright © 2015年 yuf. All rights reserved.
//

#import "AppDelegate.h"
#import "TeachViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "hDisplayView.h"

#import <AMapNaviKit/AMapNaviKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "APIKey.h"
#import "iflyMSC/IFlySpeechSynthesizer.h"
#import "iflyMSC/IFlySpeechSynthesizerDelegate.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "iflyMSC/IFlySpeechUtility.h"
#import "iflyMSC/IFlySetting.h"
#import "PayTypeViewController.h"

#import "APService.h"

@interface AppDelegate ()<LQRequestApiDelegate>{
    UINavigationController *_navController;
    CLLocationManager      *_locationmanager;
}

@property (nonatomic, strong) TeachViewController *mainViewController;
@property(nonatomic,strong)NSTimer * timer;
@property(nonatomic,assign)NSInteger  time;
@property(nonatomic,strong)UIImageView * imageView;
@property(nonatomic,strong)UIImageView * aheadImageView;
@end

@implementation AppDelegate

- (void)configureAPIKey
{
    if ([APIKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"apiKey为空，请检查key是否正确设置" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
    [AMapNaviServices sharedServices].apiKey = (NSString *)APIKey;
    [MAMapServices sharedServices].apiKey = (NSString *)APIKey;
    [AMapServices sharedServices].apiKey = (NSString *)APIKey;
}


- (void)configIFlySpeech
{
    [IFlySpeechUtility createUtility:[NSString stringWithFormat:@"appid=%@,timeout=%@",@"5565399b",@"20000"]];
    
    [IFlySetting setLogFile:LVL_NONE];
    [IFlySetting showLogcat:NO];
    
    // 设置语音合成的参数
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"50" forKey:[IFlySpeechConstant SPEED]];//合成的语速,取值范围 0~100
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"50" forKey:[IFlySpeechConstant VOLUME]];//合成的音量;取值范围 0~100
    
    // 发音人,默认为”xiaoyan”;可以设置的参数列表可参考个 性化发音人列表;
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"xiaoyan" forKey:[IFlySpeechConstant VOICE_NAME]];
    
    // 音频采样率,目前支持的采样率有 16000 和 8000;
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"8000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
    
    // 当你再不需要保存音频时，请在必要的地方加上这行。
    [[IFlySpeechSynthesizer sharedInstance] setParameter:nil forKey:[IFlySpeechConstant TTS_AUDIO_PATH]];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [UIApplication sharedApplication].idleTimerDisabled = TRUE;
    
        //高德地图
    [self configureAPIKey];
    [self configIFlySpeech];
    
    //分享集成
    [UMSocialData setAppKey:UmengAppkey];
    //设置微信AppId，设置分享url，默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:@"wx31fccdffa8db014b" appSecret:@"2aae0c82a18805dce2d94ac0fde77008" url:QW_SHARE_ADRESS];
    [UMSocialQQHandler setQQWithAppId:@"1105628260" appKey:@"KEY4bq8DkqwMVBN5PAK" url:QW_SHARE_ADRESS];
    
    
    
    //添加推送
    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
#else
    //categories 必须为nil
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
#endif
    // Required
    [APService setupWithOption:launchOptions];

   
      
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 568), NO)];
    _imageView.backgroundColor = [UIColor clearColor];
    _imageView.image = [UIImage imageNamed:@"启动页"];

    //加载主视图
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self.mainViewController = [secondStroyBoard instantiateInitialViewController];
    self.flipBoardNVC = [[FlipBoardNavigationController alloc]initWithRootViewController:self.mainViewController];
    //单例保存FlipBoardNavigationController实例
    [Common setNavigation:self.flipBoardNVC];
    self.window.rootViewController = self.flipBoardNVC;
    [self.window makeKeyAndVisible];

    [_window addSubview:_imageView];
    
    int64_t delayInSeconds = 1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self getWelcomeImage];
    });

    _timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    [self startTimer];
    
//    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
//    }
//    else{
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
//    }
//    
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
//        // 这里判断是否第一次
//        hDisplayView *hvc = [[hDisplayView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//        [self.window.rootViewController.view addSubview:hvc];
//        [UIView animateWithDuration:0.25 animations:^{
//            hvc.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//        }];
//        
//    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.


}

//---------------------------------------------推送信息

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [APService registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
    
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
    
}
#endif
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [APService handleRemoteNotification:userInfo];
    
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [APService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
    
    
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
    
}



+ (AppDelegate *)sharedAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

#pragma mark 登陆======================================================
- (void)ShowLoginPage
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Login"];
    [self.window.rootViewController presentViewController:page animated:YES completion:^{}];
}
#pragma mark 支付宝======================================================
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    //跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
    }];
    
    //微信支付
    PayTypeViewController *payment = [[PayTypeViewController alloc] init];
    [WXApi handleOpenURL:url delegate:payment];
    return YES;
}

#pragma mark  获取首页启动页--=========================================
-(void)getWelcomeImage{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"4" forKey:@"Id"];
    self.shareApi = [LQRequestApi sharedInstance];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryAdvertismentById withHttpType:@"POST" withTag:JY_JY_queryAdvertisment];
}


#pragma mark -- Timer

- (void)changeTime{
    
    _time ++;
    if (_time == 4) {
        [self stopTimer];
    }
}

- (void)startTimer{
    _time = 0;
    [_timer fire];
}

- (void)stopTimer{
    [_imageView removeFromSuperview];
    [_aheadImageView removeFromSuperview];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"welcome" object:nil];
    [_timer invalidate];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag == JY_JY_queryAdvertisment){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            
            NSString * image = [Common stringFromData:database[@"result"][0][@"titleimg"]];
                _aheadImageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 568), NO)];
                _aheadImageView.backgroundColor = [UIColor clearColor];
                [_aheadImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
                [_window addSubview:_aheadImageView];
                _timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
            [self startTimer];
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //    [self dismissWaitDialog];
    
}

@end